package net.kem.android.positioner;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;

// 1;2.26;0507362270
/**
<message>
	<distance>in meters</distance>
	<interval>in seconds</interval>
</message>
 * @author Evgeny.Kurtser
 *
 */
public class ServerResponse {
	private int gpsRefreshDistance;
	private int gpsRefreshInterval;
	private static final Pattern LOCATION_RESPONSE = Pattern.compile(".+<distance>(\\d+)</distance><interval>(\\d+)</interval>.+");

	static final ServerResponse ERROR_RESPONSE = new ServerResponse(Integer.MIN_VALUE, Integer.MIN_VALUE);
	private ServerResponse(int gpsRefreshDistance, int gpsRefreshInterval) {
		this.gpsRefreshDistance = gpsRefreshDistance;
		this.gpsRefreshInterval = gpsRefreshInterval;
	}

	static ServerResponse parseServerResponse(String response) {
		ServerResponse res;
		if(response != null && response.length() > 0) {
			Matcher m = LOCATION_RESPONSE.matcher(response);
			if(m.matches()) {
				try {
					int distance = Integer.parseInt(m.group(1));
					int interval = Integer.parseInt(m.group(2));
					res = new ServerResponse(distance, interval);
					return res;
				} catch (NumberFormatException e) {
					Log.e("parseServerResponse", "Invalid server response: " + response);
				}
			} else {
				Log.e("parseServerResponse", "Invalid server response: " + response);				
			}
		}
		return ERROR_RESPONSE;
	}

	int getGpsRefreshDistance() {
		return gpsRefreshDistance;
	}

	void setGpsRefreshDistance(int gpsRefreshDistance) {
		this.gpsRefreshDistance = gpsRefreshDistance;
	}

	int getGpsRefreshInterval() {
		return gpsRefreshInterval;
	}

	void setGpsRefreshInterval(int gpsRefreshInterval) {
		this.gpsRefreshInterval = gpsRefreshInterval;
	}

	static ServerResponse getErrorResponse() {
		return ERROR_RESPONSE;
	}
}